﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace SalaryChannel.Web
{
    [Serializable]
    public class XDataTable
    {
        public string XmlString
        {
            set;
            get;
        }
        private List<string> _columns;

        public List<string> Columns
        {
            get { return _columns; }
        }

        public string TableName
        {
            set;
            get;
        }

        public XDataTable(System.Data.DataTable table)
        {
            _columns = new List<string>(table.Columns.Count);
            TableName = table.TableName;

            foreach (System.Data.DataColumn col in table.Columns)
            {
                _columns.Add(col.ColumnName);
            }
            XmlString = ToXml(table);
        }


        /// <summary>
        /// 将DataTable序列化为字符串
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static string ToXml(System.Data.DataTable table)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (string.IsNullOrEmpty(table.TableName))
            {
                table.TableName = Guid.NewGuid().ToString();
            }
            string xml = string.Empty;
            using (MemoryStream ms = new MemoryStream())
            {

                try
                {
                    table.WriteXml(ms);
                    byte[] buffer = new byte[ms.Length];
                    ms.Read(buffer, 0, buffer.Length);
                    xml = Encoding.UTF8.GetString(ms.ToArray());
                }
                catch (Exception ex)
                {

                    throw new Exception("序列化失败，" + ex.Message);
                }
            }
            return xml;
        }
    }
}
